<?php

Yii::import('application.models._base.BaseUser');

class User extends BaseUser
{
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}

    /**
     * @return array
     *  -1 用户名必须填写
     *  -2 用户名不得有@
     *  -4密码必须填写
     *  -5密码不得大于30个字符
     *  -6密码不得小于2个字符
     *  -8 用户名是否存在【添加】
     *  -9邮箱必须填写
     *  -10 邮箱已存在【添加】
     *  -11 邮箱格式不正确
     *  -12 邮箱不得大于50个字符
     *  -19用户名是否存在【修改】
     *  -21邮箱已存在【修改】
     * -22昵称必须填写
     * -23昵称不得大于30个字符
     * -24昵称不得小于2个字符
     * 昵称已存在 -25
     * 昵称已存在 -26
     */
    public function rules()
    {
        return array(
            array('username','checkName','on'=>'create'),//用户名已存在 -8【添加】
            array('username','checkUSName','on'=>'update'),//用户名已存在 -19【修改】
            array('username', 'required','message'=>'-1','on'=>'create,update'),//用户名必须填写
            array('username','match','pattern'=>'/^[\w]{2,20}$/i','message'=>'-2','on'=>'create,update'),
            //判断登录用户名是否是邮箱
            array('password', 'required','message'=>'-4','on'=>'create'),//密码必须填写
            array('password', 'length', 'max'=>30,'tooLong'=>'-5','on'=>'create'),//密码不得大于30个字符
            array('password', 'length', 'min'=>2,'tooShort'=>'-6','on'=>'create'),//密码不得小于2个字符
            array('email', 'required','message'=>'-9','on'=>'create'),//邮箱必须填写
            array('email','email','message'=>'-11','on'=>'create'),//邮箱格式不正确
            array('email', 'length', 'max'=>50,'tooLong'=>'-12','on'=>'create'),//邮箱不得大于50个字符
            array('email','checkEmail','on'=>'create'),//邮箱已存在 -10
            array('email','checkUSEmail','on'=>'update'),//邮箱已存在 -21
            array('nick_name', 'required','message'=>'-22','on'=>'create'),//-22昵称必须填写
            array('nick_name', 'length', 'max'=>30,'tooLong'=>'-23','on'=>'create'),//-23昵称不得大于30个字符
            array('nick_name', 'length', 'min'=>2,'tooShort'=>'-24','on'=>'create'),//-24昵称不得小于2个字符
            array('nick_name','checkNickName','on'=>'create'),//昵称已存在 -25
            array('nick_name','checkUSNickName','on'=>'update'),//昵称已存在 -26
            array('password', 'safe','on'=>'update'),
            array('phone,level,province,fingerprint,group_id,recommend,recommend_time,role_salt,total_shares, total_forward,total_favorite_album,total_favorite_share,total_albums,total_follows,total_followers,create_time,domain,is_domain,update_username,sex,nick_name,avatar_public,feeling,bg,info_status, email_token, email_token_exptime,last_login_time,last_login_ip,role,loginnum,salt,repid,reg_type,avatar_status,belong_city,is_system', 'safe'),
            array('phone,level,province,fingerprint,group_id,recommend,recommend_time,role_salt,total_shares, total_forward,total_favorite_album,total_favorite_share,total_albums,total_follows,total_followers,id, username,domain,is_domain,nick_name,avatar_public,feeling,bg,info_status, email_token, email_token_exptime,last_login_time,last_login_ip,role,loginnum, status, password, email,reg_type, create_time,salt,repid,avatar_status,belong_city,is_system', 'safe', 'on'=>'search'),
        );
    }
    public function checkNickName($attribute,$params){
        $info = $this->findByAttributes(array('username'=>$this->nick_name,'status'=>1));
        if($info){
            $this->addError($attribute,'-25');
        }
    }
    public function checkUSNickName($attribute,$params){
        $uinfo = User::model()->findByPk($this->id);
        $info = $this->findByAttributes(array('nick_name'=>$this->nick_name));
        if($this->nick_name != $uinfo->nick_name && $this->nick_name ){
            if($info){
                $this->addError($attribute,'-19');
            }
        }
    }
    public function checkName($attribute,$params){
        $info = $this->findByAttributes(array('username'=>$this->username,'status'=>1));
        if($info){
            $this->addError($attribute,'-8');
        }
    }

    public function checkUSName($attribute,$params){
        $uinfo = User::model()->findByPk($this->id);
        $info = $this->findByAttributes(array('username'=>$this->username));
        if($this->username != $uinfo->username && $this->username ){
            if($info){
                $this->addError($attribute,'-19');
            }
        }
    }
    public function checkEmail($attribute,$params){
        $info = $this->findByAttributes(array('email'=>$this->email,'status'=>1));
        if($info){
            $this->addError($attribute,'-10');
        }
    }
    public function checkUSEmail($attribute,$params){
        $uinfo = User::model()->findByPk($this->id);
        $info = $this->findByAttributes(array('email'=>$this->email,'status'=>1));
        if($this->email != $uinfo->email && $this->email ){
            if($info){
                $this->addError($attribute,'-21');
            }
        }
    }
    public function beforeSave(){
        //如果是新增
        if($this->isNewRecord){
            $this->create_time = time();
            $this->salt = Xtutuquan::randStr(6);
            $this->regip = Xtutuquan::getClientIP();
            $this->password = sha1($this->password.$this->salt);
            $this->email_token = '';
            $this->email_token_exptime = '';//过期时间为24小时后
            $this->is_domain = '';
            $this->avatar_status = 0;
            $this->status = 1;
            $this->role = 0;
            $this->avatar_public = rand(1, 22);
            $this->bg = './uploads/public/bg/' . rand(1, 10) . '.jpg';
            $this->domain =  Xtutuquan::randStr(20);
        }
        return true;
    }
    //添加
    public function create($username,$password,$nickname,$email,$sex,$phone){
        $User = new User();
        $User->setScenario('create');
        $username = CHtml::encode($username);
        $password = CHtml::encode($password);
        $email = CHtml::encode($email);
        $nick_name = CHtml::encode($nickname);
        $data = array(
            'username'=>$username,
            'password'=>$password,
            'email' => $email,
            'nick_name'=>$nick_name,
            'sex'=>$sex,
            'phone'=>$phone,
            'group_id'=>Yii::app()->params['regGroupId'],//用户组  等以后扩展用户组相关 目前为1
            'belong_city'=>1,
            'is_system'=>1
        );
        $User->setAttributes($data);
        if($User->save()){
            $id = $User->attributes['id'];
            return 1;
        }else{
           return Xtutuquan::returnError($User->getErrors());
        }
    }



    public function getUser($id){
        $db = Yii::app()->db->createCommand();
        $db->select('id,username,email,nick_name,sex,phone');
        $db->from('{{user}}');
        $db->andWhere('id=:id',array(':id'=>$id));
        $info = $db->queryRow();
        return $info;
    }
    public function edit($id,$username,$password,$nickname,$email,$sex,$phone){
        $info = User::model()->findByPk($id);
        $info->setScenario('update');
        $username = CHtml::encode($username);
        $password = CHtml::encode($password);
        $email = CHtml::encode($email);
        $nick_name = CHtml::encode($nickname);
        $data = array();
        if($password){

            $data['password'] = sha1($password.$info->salt);
        }
        $data['username'] = $username;
        $data['email'] = $email;
        $data['nick_name'] = $nick_name;
        $data['sex'] = $sex;
        $data['phone'] = $phone;
        $data['group_id'] = Yii::app()->params['regGroupId'];
        $info->setAttributes($data);
        if($info->save()){
            return 1;
        }else{
            return Xtutuquan::returnError($info->getErrors());
        }
    }













    /**
     * 通过输入的用户名查取用户信息
     */
    public function findUserInfo($username){
        $result = $this->find('username=:name and role >:role',array(':name'=>CHtml::encode($username),':role'=>0));
        return $result;
    }
    public function getList($page,$rows,$order,$sort,$username,$date_from, $date_to){
        $db = Yii::app()->db->createCommand();
        $db->select('id,username,nick_name,phone,level,email,create_time,last_login_time,last_login_ip,status');
        $db->from('{{user}}');
        if ($username) {
            $db->andWhere(array('like', 'username', '%'.$username.'%'));
        }
        if ($date_from && $date_to) {
            $db->andWhere('create_time>:create_time',array(':create_time'=>$date_from));
            $db->andWhere('create_time<:create_time1',array(':create_time1'=>$date_to));
        } elseif ($date_from) {
            $db->andWhere('create_time>:create_time',array(':create_time'=>$date_from));
        } elseif ($date_to) {
            $db->andWhere('create_time<:create_time1',array(':create_time1'=>$date_to));
        }
        $db->order($sort.' '.$order);
        $db->limit($rows, ($rows * ($page - 1)));
        $info = $db->queryAll();
        foreach($info as $key=>$value){
            $info[$key]['username'] = $value['username'].'&nbsp;&nbsp;<i style="padding: 6px;cursor:pointer;" onclick="user_tool.show(\''.$value['id'].'\')" class="icon-bullet_magnify"></i>';
            $info[$key]['create_time'] = date('Y-m-d',$value['create_time']);
            $info[$key]['last_login_time'] = date('Y-m-d',$value['last_login_time']);
            $info[$key]['status'] = $value['status'] ? '<i  onclick="user_tool.setStatus(\''.$value['id'].'\',0)"  style="padding: 6px;" class="icon-bullet_tick"></i>' : '<i  onclick="user_tool.setStatus(\''.$value['id'].'\',1)"  class="icon-bullet_cross"  style="padding: 6px;" ></i>';
        }
        return array(
            'rows'=>$info ? $info : '',
            'total'=>$this->getTotal($username,$date_from, $date_to)
        );
    }
    private function getTotal($username,$date_from, $date_to){
        $db = Yii::app()->db->createCommand();
        $db->select('COUNT(*) AS count');
        $db->from('{{user}}');
        if ($username) {
            $db->andWhere(array('like', 'username', '%'.$username.'%'));
        }
        if ($date_from && $date_to) {
            $db->andWhere('create_time>:create_time',array(':create_time'=>$date_from));
            $db->andWhere('create_time<:create_time1',array(':create_time1'=>$date_to));
        } else if ($date_from) {
            $db->andWhere('create_time>:create_time',array(':create_time'=>$date_from));
        } else if ($date_to) {
            $db->andWhere('create_time<:create_time1',array(':create_time1'=>$date_to));
        }
        $info = $db->queryRow();
        return $info['count'];
    }
    //删除
    public function remove($ids){
        UserExtend::model()->deleteAll('uid in('.$ids.')');
        UserBind::model()->deleteAll('uid in('.$ids.')');
        return $this->deleteAll('id in('.$ids.')');
    }

    /**
     * 验证字段
     */
    public function checkField($field,$type){
        $this->setScenario('create');
        $data = array();
        switch($type){
            case 'username' :
                $data['username'] = $field;
                break;
            case 'email':
                $data['email'] = $field;
                break;
            default:
                return 0;
        }
        $this->setAttributes($data);
        $this->save($data);
        $error = $this->getErrors();
        switch($error[$type][0]){
            case '-8' :
                return -1;
                break;
            case '-10':
                return -1;
                break;
            default:
                return 1;
        }
    }




}